var HSSync = function () {

    this.$grid_selector = $("#jira_sync_grid_table");
    this.pager_selector = "#jira_sync_grid_pager";

    // 最后搜索内容
    this.lastSearch = '';

    // 请求url
    this.URL = {
        SYNC: '/jira/hs/sync/{{id}}',
        AGAIN_SYNC: '/jira/hs/again/sync/{{soDemandId}}',
        RECALL_SYNC: '/jira/hs/recall/sync/{{soDemandId}}',
        DELETE_RECALL_SYNC: '/jira/hs/delete/recall/sync/{{soDemandId}}',
        RESPONSE_SYNC: '/jira/hs/response/{{id}}'
    };

    var self = this;
    this.colModel = [
        {name: 'id', label: 'ID', hidden: true, width: 15, key: true},
        {name: 'soDemandId', label: '恒生需求ID', hidden: true},
        {name: 'issueKey', label: 'IssueKey', fixed: true, width: 100},
        {name: 'productName', label: '产品名称', width: 10},
        {name: 'remark', label: '需求说明', width: 30},
        {
            name: 'success', label: '同步是否成功', fixed: true, width: 100, formatter: function (cellValue) {
                if (cellValue) {
                    return '成功';
                } else {
                    return '<span class="red">失败</span>';
                }
            }
        },
        {
            name: 'createdAt', label: '创建日期', fixed: true, width: 140, formatter: "date",
            formatoptions: {srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s'}
        },
        {
            label: '操作', fixed: true, width: 360, sortable: false, formatter: function (cellValue, row, data) {
                if (undefined !== data.soDemandId && null !== data.soDemandId && '' !== data.soDemandId) {
                    return self.operatingTemplate({rowId: row.rowId});
                } else {
                    return self.operatingTemplateTwo({rowId: row.rowId});
                }
            }
        }
    ];

    this.operatingTemplate = _.template(
        '<div class="btn-group">' +
        '<button data-response-sync-hs="{{rowId}}" class="btn btn-sm btn-info response_sync_hs">响应信息</button>' +
        '<button data-recall-sync-hs="{{rowId}}" class="btn btn-sm btn-primary recall_sync_hs">撤回需求</button>' +
        '<button data-again-sync-hs="{{rowId}}" class="btn btn-sm btn-primary again_sync_hs">重新同步</button>' +
        '<button data-delete-recall-sync-hs="{{rowId}}" class="btn btn-sm btn-danger delete_recall_sync_hs">删除已撤回需求</button>' +
        '</div>'
    );

    this.operatingTemplateTwo = _.template(
        '<div class="btn-group">' +
        '<button data-response-sync-hs="{{rowId}}" class="btn btn-sm btn-info response_sync_hs">响应信息</button>' +
        '<button data-sync-hs="{{rowId}}" class="btn btn-sm btn-primary sync_hs">同步</button>' +
        '</div>'
    );


    this.options = {
        moduleKey: 'jira/hs',
        pager: this.pager_selector,
        sortname: 'createdAt',
        caption: "恒生同步列表",
        colModel: this.colModel,
        navbarDefaultIcon: {
            add: false,
            edit: false,
            view: false,
            del: false
        }
    };

};

HSSync.prototype = {
    // 初始化表格
    initGird: function () {

        var self = this;
        this.$grid_selector
            .xumf_jqGird(this.options)
            .xumf_jqGird('navGrid', this.pager_selector)
            .jqGrid('navButtonAdd', this.pager_selector,
                {
                    caption: '',
                    title: "查看",
                    buttonicon: "ui-icon ace-icon fa fa-search-plus grey",
                    onClickButton: function () {
                        $(this).getGridSelectedRow(function (rowData) {
                            self.viewRow(rowData);
                        });
                    },
                    position: "first"
                })
            .jqGrid('navButtonAdd', this.pager_selector,
                {
                    caption: '',
                    title: "搜索",
                    buttonicon: "fa fa-search orange",
                    onClickButton: function () {
                        self.searchUI();
                    },
                    position: "first"
                });
        // 绑定事件
        this.$grid_selector.delegate('.sync_hs', 'click', function (event) {
            var rowId = $(event.currentTarget).data('sync-hs');
            var row = self.$grid_selector.jqGrid('getRowData', rowId);
            self.syncUI(row.id);
        });
        this.$grid_selector.delegate('.again_sync_hs', 'click', function (event) {
            var rowId = $(event.currentTarget).data('again-sync-hs');
            var row = self.$grid_selector.jqGrid('getRowData', rowId);
            self.againSyncUI(row.soDemandId);
        });
        this.$grid_selector.delegate('.recall_sync_hs', 'click', function (event) {
            var rowId = $(event.currentTarget).data('recall-sync-hs');
            var row = self.$grid_selector.jqGrid('getRowData', rowId);
            self.recallUI(row.soDemandId);
        });
        this.$grid_selector.delegate('.delete_recall_sync_hs', 'click', function (event) {
            var rowId = $(event.currentTarget).data('delete-recall-sync-hs');
            var row = self.$grid_selector.jqGrid('getRowData', rowId);
            self.deleteRecallUI(row.soDemandId);
        });
        this.$grid_selector.delegate('.response_sync_hs', 'click', function (event) {
            var rowId = $(event.currentTarget).data('response-sync-hs');
            var row = self.$grid_selector.jqGrid('getRowData', rowId);
            self.viewResponse(row.id);
        });
    },
    searchUI: function () {
        var self = this;
        layer.open({
            maxmin: false,
            title: '搜索',
            area: ['600px', 300],
            btn: ['搜索', '取消'],
            content: _.template('<form style="padding:12px;" class="form-horizontal">\
                        <div class="form-group">\
                            <label class="col-xs-5 control-label" for="keyword">恒生产品名称/需求说明/IssueKey：</label>\
                            <div class="col-xs-7">\
                                <input name="keyword" class="form-control" value="{{keyword}}" autocomplete="off" type="text">\
                            </div>\
                        </div>\
                    </form>')({keyword: this.lastSearch}),
            yes: function (index, layero) {
                var $form = $(layero).find('form');
                self.lastSearch = $form.find('input[name=keyword]').val();
                self.$grid_selector.setGridParam({
                    datatype: "json",
                    postData: {searchString: self.lastSearch}
                }).trigger('reloadGrid').setGridParam({
                    datatype: "json",
                    postData: {searchString: ''}
                });
                layer.close(index);
            }
        })
    },
    viewRow: function (rowData) {
        var $dl = $('<dl class="dl-horizontal"></dl>');
        this.colModel.forEach(function (item) {
            if (item.hasOwnProperty('key') || !item.hasOwnProperty('name')) {
                return false;
            }
            $dl.append(_.template('<dt>{{title}}</dt><dd>{{content}}</dd>')({
                title: item.label,
                content: rowData[item.name]
            }))
        });
        layer.open({
            title: '查看',
            area: ['600px', '250px'],
            content: $dl.prop("outerHTML"),
            btn: ['确定']
        });
    },
    viewResponse: function (id) {

        var self = this;
        var template = '<table class="table table-striped">\
                            <tbody>\
                                <tr>\
                                    <th>请求时间</th>\
                                    <th>请求类型</th>\
                                    <th>是否成功</th>\
                                    <th>响应内容</th>\
                                </tr>\
                            </tbody>\
                        </table>';
        var success = function (layero, index) {
            var $tbody = $(layero).find('table tbody');
            $.xumf.ajaxAndLoading({
                type: 'get',
                url: _.template(self.URL.RESPONSE_SYNC)({id: id})
            }).success(function (res) {
                var trTemplate = '<tr><td colspan="3">没有数据！</td></tr>';
                if (res.success) {
                    res.data.forEach(function (o) {
                        trTemplate = '<tr>\
                                        <td>{{createdAt}}</td>\
                                        <td>{{requestType}}</td>\
                                        <td>{{successContent}}</td>\
                                        <td><code>{{content}}</code></td>\
                                    </tr>';
                        var parse = JSON.parse(o.content);
                        o.successContent = parse.success ? '成功' : '<span class="red">失败</span>';
                        $tbody.append(_.template(trTemplate)(o));
                    });
                    if (res.data.length === 0) {
                        $tbody.append(trTemplate);
                    }
                } else {
                    $tbody.append(trTemplate);
                }
            });
        };

        layer.open({
            title: "恒生响应",
            area: ["650px", "300px"],
            content: template,
            success: success,
            btn: ["确定"]
        });

    },
    deleteRecallUI: function (soDemandId) {
        if ('' === soDemandId || undefined === soDemandId) {
            $.xumf.gritterError("需求id不存在，需求提交还没成功，无法删除已撤回需求！");
            return;
        }
        var self = this;
        // 显示弹框
        $.xumf.confirm("是否删除已撤回需求！", function (index, layero) {
            layer.close(index);
            self.deleteRecallAction(soDemandId);
        });
    },
    deleteRecallAction: function (soDemandId) {
        var self = this;
        var url = _.template(this.URL.DELETE_RECALL_SYNC)({soDemandId: soDemandId});
        $.xumf.ajaxAndLoading({
            type: 'post',
            url: url
        }).success(function (res) {
            res.success && self.$grid_selector.trigger("reloadGrid");
            $.xumf.gritter(res);
        });
    },
    syncUI: function (id) {
        var self = this;
        // 显示弹框
        $.xumf.confirm("是否同步需求！", function (index, layero) {
            layer.close(index);
            self.syncUIAction(id);
        });
    },
    syncUIAction: function (id) {
        var self = this;
        var url = _.template(this.URL.SYNC)({id: id});
        $.xumf.ajaxAndLoading({
            type: 'post',
            url: url
        }).success(function (res) {
            res.success && self.$grid_selector.trigger("reloadGrid");
            $.xumf.gritter(res);
        });
    },
    recallUI: function (soDemandId) {
        if ('' === soDemandId || undefined === soDemandId) {
            $.xumf.gritterError("需求id不存在，需求提交还没成功，无法撤销需求！");
            return;
        }
        var self = this;
        // 显示弹框
        $.xumf.confirm("是否撤回需求！", function (index, layero) {
            layer.close(index);
            self.recallAction(soDemandId);
        });
    },
    recallAction: function (soDemandId) {
        var self = this;
        var url = _.template(this.URL.RECALL_SYNC)({soDemandId: soDemandId});
        $.xumf.ajaxAndLoading({
            type: 'post',
            url: url
        }).success(function (res) {
            res.success && self.$grid_selector.trigger("reloadGrid");
            $.xumf.gritter(res);
        });
    },
    againSyncUI: function (soDemandId) {
        var self = this;
        // 显示弹框
        $.xumf.confirm("重新同步需求到恒生！", function (index, layero) {
            layer.close(index);
            self.againSyncAction(soDemandId);
        });
    },
    /**
     * 验证与提交
     * @returns {*} 验证是否成功
     * @param soDemandId
     */
    againSyncAction: function (soDemandId) {
        var self = this;
        var url = _.template(this.URL.AGAIN_SYNC)({soDemandId: soDemandId});
        $.xumf.ajaxAndLoading({
            type: 'post',
            url: url
        }).success(function (res) {
            res.success && self.$grid_selector.trigger("reloadGrid");
            $.xumf.gritter(res);
        });
    }
};

